const express = require("express");
const router = express.Router();
const passport = require("passport");
const CashReturn = require("../../../models/CashReturn");
const auth = passport.authenticate("jwt", { session: false });
const errorHandler = require("../../../middlewares/errorHandler");

// @route  GET api/returncash/test
router.get("/test", (req, res) => res.json({ msg: "returncash works" }));

// @route  POST api/returncash/add
router.post("/add", auth, async (req, res) => {
  try {
    const cashReturn = await CashReturn.create(req.body);
    console.log("添加数据成功:", cashReturn);
    res.status(200).json({ success: true, data: cashReturn });
  } catch (err) {
    errorHandler(res, err);
  }
});

// @route  GET api/returncash
router.get("/", auth, async (req, res) => {
  try {
    const cashReturns = await CashReturn.find();
    console.log("获取数据成功:", cashReturns);
    res
      .status(200)
      .json({ success: true, count: cashReturns.length, data: cashReturns });
  } catch (err) {
    errorHandler(res, err);
  }
});

// @route  GET api/returncash/:id
router.get("/:id", auth, async (req, res) => {
  try {
    const cashReturn = await CashReturn.findById(req.params.id);
    if (!cashReturn) {
      console.error("未查找到数据");
      return res.status(404).json({ success: false, error: "未查找到数据" });
    }
    console.log("获取数据成功", cashReturn);
    res.status(200).json({ success: true, data: cashReturn });
  } catch (err) {
    errorHandler(res, err);
  }
});

// @route  POST api/returncash/edit
router.post("/edit", auth, async (req, res) => {
  try {
    const { _id, ...updateData } = req.body;
    const cashReturn = await CashReturn.findByIdAndUpdate(_id, updateData, {
      new: true,
    });
    if (!cashReturn) {
      console.error("未查找到数据");
      return res.status(404).json({ success: false, error: "未查找到数据" });
    }
    console.log("编辑数据成功:", cashReturn);
    res.status(200).json({ success: true, data: cashReturn });
  } catch (err) {
    errorHandler(res, err);
  }
});

// @route  DELETE api/returncash/delete
router.delete("/delete", auth, async (req, res) => {
  try {
    const { _id } = req.body;
    const cashReturn = await CashReturn.findByIdAndRemove(_id);
    if (!cashReturn) {
      console.error("未查找到数据");
      return res.status(404).json({ success: false, error: "未查找到数据" });
    }
    console.log("删除数据成功:", cashReturn);
    res.status(200).json({ success: true, data: cashReturn });
  } catch (err) {
    errorHandler(res, err);
  }
});

module.exports = router;
